<template>
	<view class="container">
		<!-- 地图容器 -->
		<map id="map" :latitude="center.latitude" :longitude="center.longitude" :scale="16" class="map-container"
			show-location :enable-scroll="false">
		</map>
		<view class="uni-flex-column content">
			<view class="address">
				<view class="uni-flex uni-align-center" v-if="valiFormData?.lng > 0 && valiFormData?.lat > 0">
					<view class="uni-flex-column" style="flex: 1">
						<text class="name">{{ valiFormData?.name }}</text>
						<text class="detail">{{
              valiFormData?.provinceLive +
              valiFormData?.cityLive +
              valiFormData?.areaLive +
              valiFormData?.address
            }}</text>
					</view>
					<view class="update-address" @click="updateAddress">修改地址</view>
				</view>
				<view class="select-address" @click="updateAddress" v-else>选择地址 <uni-icons type="right" size="14"
						color="#2f80ed"></uni-icons>
				</view>
			</view>
			<view class="info">
				<uni-forms ref="valiForm" :modelValue="valiFormData">
					<view class="uni-flex uni-align-center formLabel">
						<text class="label">门牌号</text>
						<uni-easyinput v-model="valiFormData.doorNumber" placeholder="详细地址,例1层101室"></uni-easyinput>
					</view>
					<view class="uni-flex uni-align-center formLabel">
						<text class="label">标签</text>
						<view v-for="(item, index) in labelData" :key="index" class="tag"
							:class="[valiFormData.label == item.value ? 'tag--active' : 'tag--normal']"
							@click="handleSelect(item)">
							{{ item.name }}
						</view>
					</view>
					<view class="uni-flex uni-justify-between uni-align-center formLabel">
						<view class="uni-flex uni-align-center" style="flex: 1">
							<text class="label">联系人</text>
							<uni-easyinput v-model="valiFormData.contacts" placeholder="请填写姓名"
								style="width: 100rpx"></uni-easyinput>
						</view>
						<view class="uni-flex uni-align-center">
							<view v-for="(item, index) in labelSexData" :key="index"
								class="uni-flex uni-align-center sex" :class="{ 'first-sex': index === 0 }"
								@click="valiFormData.sex = item.value">
								<image :src="`${$ImgBaseUrl}select_normal.png`" mode="widthFix"
									v-if="valiFormData.sex !== item.value" />
								<image :src="`${$ImgBaseUrl}select_active.png`" mode="widthFix"
									v-if="valiFormData.sex === item.value" />
								<text> {{ item.name }}</text>
							</view>
						</view>
					</view>
					<view class="uni-flex uni-align-center formLabel">
						<text class="label">手机号</text>
						<uni-easyinput v-model="valiFormData.phone" placeholder="请填写手机号" type="number"></uni-easyinput>
					</view>
				</uni-forms>
				<view class="save" @click="saveAddress">保存地址</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		addAddressBook,
		updateAddressBook
	} from "@/api/address.js";
	import {
		ref,
		onMounted,
		reactive,
		getCurrentInstance
	} from "vue";
	// 获取通信通道
	const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel()
	const labelData = ref([{
		name: "家",
		value: "HOME"
	}, {
		name: "公司",
		value: "COMPANY"
	}, {
		name: "学校",
		value: "SCHOOL"
	}]);
	const labelSexData = ref([{
		'name': '先生',
		'value': 0
	}, {
		'name': '女士',
		'value': 1
	}]);
	const valiForm = ref();

	// 表单数据
	const valiFormData = reactive({
		id: "",
		doorNumber: "", // 门牌号
		label: "", // 标签（HOME/家，COMPANY/公司，SCHOOL/学校）
		sex: -1, // 性别
		contacts: "", // 联系人
		phone: "", // 联系人电话
		address: "", // 详细地址
		provinceCode: "",
		provinceLive: "",
		cityCode: "",
		cityLive: "",
		areaCode: "",
		areaLive: "",
		landmark: "",
		lat: 0,
		lng: 0
	});
	const handleSelect = (item) => {
		valiFormData.label = item.value;
	};
	// 坐标数据
	const center = ref({
		latitude: 39.90469,
		longitude: 116.40717
	});
	// 获取用户位置
	const getLocation = async () => {
		try {
			await uni.authorize({
				scope: "scope.userLocation",
				fail: () => {
					uni.showModal({
						title: "提示",
						content: "需要位置权限才能使用地图功能",
						confirmText: "去设置",
						success: (res) => {
							if (res.confirm) uni.openSetting();
						},
					});
					throw new Error("用户拒绝授权");
				},
			});

			const res = await new Promise((resolve, reject) => {
				uni.getLocation({
					type: "gcj02",
					success: resolve,
					fail: reject,
				});
			});

			center.value = {
				latitude: res.latitude,
				longitude: res.longitude,
			};
			return res;
		} catch (err) {
			console.warn("获取位置失败:", err);
			return center.value;
		}
	};
	const updateAddress = () => {
		uni.navigateTo({
			url: "/pages/tabBars/serviceAddress/selectMap",
			events: {
				// 定义接收事件
				acceptDataFromPageB: (data) => {
					const dataInit = data.message;
					const [longitude, latitude] = dataInit.location.split(',');
					Object.assign(valiFormData, {
						provinceLive: dataInit?.province,
						cityLive: dataInit?.city,
						areaLive: dataInit?.area,
						landmark: dataInit?.name,
						address: dataInit?.address,
						lng: Number(longitude),
						lat: Number(latitude),
						provinceCode: dataInit?.citycode,
						cityCode: dataInit?.citycode,
						areaCode: dataInit?.adcode,
					});
				},
			},
			success: (res) => {
				// 发送初始数据（可选）
				res.eventChannel.emit("sendDataToPageB", {
					initData: valiFormData,
				});
			},
		});
	};
	// 初始化
	onMounted(async () => {
		const location = await getLocation();
		//修改地址的时候需要用到
		eventChannel.on('sendDataToPageB', (data) => {
			if (data.initData) {
				const dataInit = data.initData
				// 只更新你需要的字段（保持响应性）
				// 安全赋值方法
				Object.keys(dataInit).forEach(key => {
					if (key in valiFormData) {
						valiFormData[key] = dataInit[key] ?? valiFormData[
							key] // 保留原值如果response字段为null
					}
				})
			}
			console.log('收到PageA数据:', data)
		})
	});
	const saveAddress = () => {
		const params = {
			...valiFormData,
		};
		if (params.sex === -1) delete params.sex;
		uni.showLoading({
			title: "保存中",
		});
		const request = params.id ? updateAddressBook : addAddressBook;
		request(params)
			.then((res) => {
				if (res.code === 200) {
					if (params.id) {
						uni.showToast('保存成功')
					} else {
						uni.showToast('修改成功')
					}
					console.log(res);
					eventChannel.emit('acceptDataFromPageB', {
						status: 'success'
					})
					uni.navigateBack()
				} else {
					uni.showToast({
						title: "添加失败",
						icon: 'none'
					})
				}
				uni.hideLoading();
			})
	}
</script>
<style lang="scss">
	.is-input-border {
		border: none !important;
		font-size: 28rpx;
	}

	.uni-easyinput {
		width: 100rpx;
	}
</style>
<style lang="scss" scoped>
	.container {
		position: relative;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.map-container {
			width: 100%;
			height: 100vh;
		}

		.content {
			position: absolute;
			top: 292rpx;
			left: 24rpx;
			right: 24rpx;
			bottom: 0;

			.address {
				background: white;
				border-radius: 20rpx;
				padding: 22rpx 25rpx;
				align-items: center;

				.name {
					font-weight: 500;
					font-size: 32rpx;
					color: #303133;
				}

				.detail {
					font-weight: 400;
					font-size: 28rpx;
					color: #666666;
					margin-top: 10rpx;
				}

				.update-address {
					padding: 0 32rpx;
					height: 56rpx;
					line-height: 56rpx;
					font-size: 24rpx;
					color: #2f80ed;
					border-radius: 28px;
					border: 1px solid #2f80ed;
				}

				.select-address {
					border: 1px solid #2f80ed;
					font-size: 24rpx;
					color: #2f80ed;
					border-radius: 10px;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
				}
			}

			.info {
				flex: 1;
				background: white;
				border-radius: 20rpx;
				padding: 22rpx 0;
				margin-top: 18rpx;

				.formLabel {
					padding: 0 25rpx;
					height: 100rpx;
					border-bottom: 1px solid #e2e2e2;

					.label {
						width: 120rpx;
						font-weight: 500;
						font-size: 28rpx;
						color: #303133;
					}

					.tag {
						font-size: 28rpx;
						padding: 10rpx 30rpx;
						border-radius: 6px;
						cursor: pointer;
						/* 禁用默认点击高亮 */
						-webkit-tap-highlight-color: transparent;

						/* 核心优化：仅对背景色和文字颜色添加过渡 */
						transition: background-color 0.3s ease, color 0.2s ease;
						will-change: background-color, color;
						/* 提升性能 */
						margin-right: 16rpx;

						&--normal {
							background: #f1f1f1;
							color: #333333;
						}

						&--active {
							background: #e5f0ff;
							color: #2f80ed;
						}
					}

					.sex {
						font-size: 28rpx;
						color: #303133;

						image {
							width: 30rpx;
							height: 30rpx;
							margin-right: 10rpx;
						}
					}

					.first-sex {
						margin-right: 48rpx !important;
					}
				}

				.save {
					height: 88rpx;
					line-height: 88rpx;
					text-align: center;
					background: #2f80ed;
					border-radius: 44rpx;
					font-size: 32rpx;
					color: #ffffff;
					margin: 75rpx 24rpx 0 24rpx;
				}
			}
		}
	}
</style>